package org.zjx.swing.util;

import org.zjx.swing.bean.ColorRecord;
import org.zjx.swing.model.LiterateModel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

// 修改后的颜色列表渲染器
public class ColorItemRenderer extends DefaultListCellRenderer {
    public LiterateModel model;

    public ColorItemRenderer(LiterateModel model) {
        this.model = model;
    }

    @Override
    public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        if (value instanceof ColorRecord) {
            ColorRecord item = (ColorRecord) value;
            JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0));
            panel.setOpaque(true);
            panel.setBackground(isSelected ? list.getSelectionBackground() : list.getBackground());

            // 复选框（移除强制单选逻辑）
            JCheckBox checkBox = new JCheckBox();
            checkBox.setSelected(item.isChecked());
            checkBox.setOpaque(false);

            // 添加ItemListener（保持状态同步）
            checkBox.addItemListener(new ItemListener() {
                @Override
                public void itemStateChanged(ItemEvent e) {
                   model.getColorRecords().get(index).setChecked(checkBox.isSelected());
                    // 更新列表选择状态
                    if (checkBox.isSelected()) {
                        list.getSelectionModel().addSelectionInterval(index, index);
                    } else {
                        list.getSelectionModel().removeSelectionInterval(index, index);
                    }
                }
            });

            panel.add(checkBox);

            // 颜色预览和标签（保持不变）
            JPanel colorPanel = new JPanel();
            colorPanel.setPreferredSize(new Dimension(20, 20));
            colorPanel.setBackground(new Color(item.getR(), item.getG(), item.getB()));
            panel.add(colorPanel);

            JLabel label = new JLabel(item.toString().replace("[✔] ", "").replace("[ ] ", ""));
            label.setForeground(isSelected ? list.getSelectionForeground() : list.getForeground());
            panel.add(label);

            return panel;
        }
        return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
    }
}
